#!/usr/bin/env python
"""Clean KML Files

    Usage:
        cat name.kml | ./clean_kml.py --remove-data > output.kml

    --remove-data - Removes extendeddata elements (extendeddata, ExtendedData, or extendedData)
    --remove-description - Removes description tags
    --empty-description - Sets contents of description tags to blank string
"""

__author__ = "Chad Burt (chad@underbluewaters.net)"
__copyright__ = "Copyright (c) 2010 Regents of the University of California Santa Barbara"
__license__ = "New BSD"

import sys
import getopt
import xml.dom.minidom

class KmlDocument():
    
    def __init__(self, f):
        self.dom = xml.dom.minidom.parse(f)

    def removetags(self, tagname):
        for node in self.dom.getElementsByTagName(tagname):
            node.parentNode.removeChild(node)

    def remove_data(self):
        """Removes all elements name extendeddata ExtendedData or extendedData
        """
        self.removetags('ExtendedData')
        self.removetags('extendedData')
        self.removetags('extendeddata')
    
    def remove_description(self):
        self.removetags('description')
        
    def empty_description(self):
        """Sets any description contents to an empty string.
        """
        for node in self.dom.getElementsByTagName('description'):
            node.firstChild.data = ''
    
    def render(self):
        return self.dom.toxml()

def usage():
    print __doc__

def main(argv):
    remove_data = False
    remove_description = False
    empty_description = False
    try:
        opts, args = getopt.getopt(argv, "h", 
            ["help", "remove-data", "empty-description", "remove-description"])
    except getopt.GetoptError:
        usage()
        sys.exit(2)
    for opt, arg in opts:
        if opt in ("-h", "--help"):
            usage()
            sys.exit()
        elif opt in ("--remove-data"):
            remove_data = True
        elif opt in ("--empty-description"):
            empty_description = True
        elif opt in ("--remove-description"):
            remove_description = True
            
    doc = KmlDocument(sys.stdin)
    
    if remove_data:
        doc.remove_data()
    if empty_description:
        doc.empty_description()
    if remove_description:
        doc.remove_description()
        
    print doc.render()
    

if __name__ == "__main__":
    main(sys.argv[1:])
